extends Ally

enum State{
	IDLE,
	RUN,
	REST,
	ATTACK,
}

# 攻击目标
var target = null
# 行动方向
var direction : Vector2 = Vector2.ZERO
# 移动速度
var speed = 1000
# 与目标间的距离
var distance = 0
# 执行对应状态的行动
func tick_physics(state : State,delta : float) ->void:
	match state:
		State.IDLE:
			idle()
		State.RUN:
			run(speed,delta)
		State.REST:
			rest()
		State.ATTACK:
			attack()
	

# 获取下一个状态
func get_next_state(state : State) ->State:
	# 如果目标不为空，则判断与目标的位置距离
	if target != null:
		direction = target.position-self.position
		distance = direction.length()
		if distance > 20:
			return State.RUN
		elif distance <= 20:
			return State.ATTACK
	
	match state:
		State.IDLE:
			return State.IDLE
		State.RUN:
			# 如果失去目标，则恢复IDLE状态
			if target == null:
				return State.IDLE
		State.ATTACK:
			if target == null:
				return State.IDLE
			elif distance > 20:
				return State.RUN
	return state

# 改变状态发生的变化
func transitiona_state(from : State,to : State)->void:
	match to:
		State.IDLE:
			pass
		State.RUN:
			sprite_2d.flip_h = direction.x < 0 
			pass
		State.REST:
			pass
		State.ATTACK:
			animation_player.play("attack")
			pass

# IDLE状态下执行的行动
func idle():
	animation_player.play("idle")
	pass


# RUN状态下执行的行动
func run(speed,delta):
	animation_player.play("run")
	var run_direction = (target.global_position-self.global_position).normalized()
	# sprite.flip_h = run_direction.x<0
	velocity = run_direction * speed * delta
	move_and_slide()
	pass
	
# REST状态下执行的行动
func rest():
	pass

# REST状态下执行的行动
func attack():
	var reach = weapon.get_overlapping_bodies()
	await get_tree().create_timer(0.3).timeout
	for i in reach:
		if i != null:
			if i.is_in_group("enemy"):
				i.queue_free()
			

func _on_dectect_body_shape_entered(body_rid: RID, body: Node2D, body_shape_index: int, local_shape_index: int) -> void:
	print("body enter")
	# 如果目标不存在则为目标赋值
	if target == null:
		target = body
	pass # Replace with function body.
